package cn.miao.photoprinter.activity;

import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import org.taptwo.android.widget.CircleFlowIndicator;
import org.taptwo.android.widget.ViewFlow;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import cn.miao.photoprinter.R;
import cn.miao.photoprinter.adapter.MyImageHorizalAdapter;
import cn.miao.photoprinter.database.DatabaseHelper;
import cn.miao.photoprinter.entity.ShoppingCart;
import cn.miao.photoprinter.entity.ShoppingRecord;
import cn.miao.photoprinter.util.ToastUtil;
import cn.miao.photoprinter.view.FlowRadioGroup;
import cn.miao.photoprinter.view.LoadingDialog;

public class ImageActivity extends Activity {
	private String[] path;
	private LoadingDialog loadingDialog;

	ViewFlow viewFlow;
	RadioGroup rgShops, rgPhotoSizes, rgPhotoMaterials, rgPhotoBrands;
	FlowRadioGroup rgOthers;
	TextView tvTitle;
	TextView tvNum;
	Button btAddNum, btMinusNum;
	Button btAddCart, btSendPrint;
	
	final static int SAVECART = 10001;
	final static int SAVECART_FAIL = 10002;
	
	private static Handler handler;

	private String getRealPathFromUri(Uri uri) {
		String[] proj = { MediaStore.Images.Media.DATA };
		Cursor actualimagecursor = getContentResolver().query(uri, proj, null,
				null, null);
		int actual_image_column_index = actualimagecursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		actualimagecursor.moveToFirst();
		String img_path = actualimagecursor
				.getString(actual_image_column_index);
		return img_path;
	}

	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_image);
		ArrayList<String> list = new ArrayList<String>();
		handler = new MyHandler(this);
		
		Intent intent = getIntent();
		String aciton = intent.getAction();
		String type = intent.getType();
		// System.out.println("aciton=" + aciton + ",type=" + type);
		if (null == aciton) {
			path = intent.getStringExtra("path").split(",");
			System.out.println(intent.getStringExtra("path"));
			// ImageLoader.getInstance().displayImage("file://" + path[0], iv);
			for (String uri : path) {
				list.add(uri);
			}
		} else {
			if (Intent.ACTION_SEND.equals(aciton)) {
				if ("image/jpeg".equals(type)) {
					// single image
					Uri pictureUri = (Uri) intent
							.getParcelableExtra(Intent.EXTRA_STREAM);
					list.add(getRealPathFromUri(pictureUri));
				}
			} else if (Intent.ACTION_SEND_MULTIPLE.equals(aciton)) {
				// multiple image
				ArrayList<Uri> pictureUrisArrayList = intent
						.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
				for (Uri uri : pictureUrisArrayList) {
					list.add(getRealPathFromUri(uri));
				}
			}
		}
		MyImageHorizalAdapter adapter = new MyImageHorizalAdapter(this);
		adapter.addAll(list);

		/*
		 * NoteEditor noteEditor = (NoteEditor) findViewById(R.id.note);
		 * noteEditor.setNotesMinLines(2); noteEditor.lineDis = 12;
		 */
		viewFlow = (ViewFlow) findViewById(R.id.viewflow);
		viewFlow.setSideBuffer(list.size());
		viewFlow.setAdapter(adapter);
		CircleFlowIndicator indicator = (CircleFlowIndicator) findViewById(R.id.viewflowindicator);
		viewFlow.setFlowIndicator(indicator);
		viewFlow.setTimeSpan(2000);
		viewFlow.startAutoFlowTimer(); // 启动自动播放
		
		tvTitle = (TextView) findViewById(R.id.title);
		tvTitle.setText("共" + list.size() + "张");
		tvNum = (TextView) findViewById(R.id.tvNum);
		btAddNum = (Button) findViewById(R.id.btAddNum);
		btMinusNum = (Button) findViewById(R.id.btMinusNum);
		btAddNum.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				addNum();
			}
		});
		btMinusNum.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				minusNum();
			}
		});
		rgShops = (RadioGroup) findViewById(R.id.rg_shops);
		rgPhotoBrands = (RadioGroup) findViewById(R.id.rg_photobrands);
		rgPhotoMaterials = (RadioGroup) findViewById(R.id.rg_photomaterials);
		rgPhotoSizes = (RadioGroup) findViewById(R.id.rg_photosizes);
		rgOthers = (FlowRadioGroup) findViewById(R.id.rg_others);
		btAddCart = (Button) findViewById(R.id.bt_addcart);
		btAddCart.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				save2Cart();
			}
		});
		btSendPrint = (Button) findViewById(R.id.bt_sendprint);
		btSendPrint.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				List<ShoppingCart> list = new ArrayList<ShoppingCart>();
				
				ShoppingCart record = new ShoppingCart();
				RadioButton rgShop = (RadioButton) findViewById(rgShops.getCheckedRadioButtonId());
				RadioButton rgPhotoBrand = (RadioButton) findViewById(rgPhotoBrands.getCheckedRadioButtonId());
				RadioButton rgPhotoMaterial = (RadioButton) findViewById(rgPhotoMaterials.getCheckedRadioButtonId());
				RadioButton rgPhotoSize = (RadioButton) findViewById(rgPhotoSizes.getCheckedRadioButtonId());
				String others = "";
				for (int i = 0; i < rgOthers.getChildCount(); i++) {
					CheckBox checkBox = (CheckBox) rgOthers.getChildAt(i);
					if (checkBox.isChecked()) {
						others += "," + checkBox.getText().toString();
					}
				}
				record.setShop(rgShop.getText().toString());
				record.setPhotoBrand(rgPhotoBrand.getText().toString());
				record.setPhotoMatieral(rgPhotoMaterial.getText().toString());
				record.setPhotocnt(Integer.parseInt(tvNum.getText().toString()));
				record.setPhotoSize(rgPhotoSize.getText().toString());
				record.setOthers(others);
				String paths = "";
				for (String tmp : path) {
					paths += "," + tmp;
				}
				record.setPhotos(paths);
				
				list.add(record);
				Intent intent = new Intent(ImageActivity.this,
						Cart2OrderActivity.class);
				intent.putExtra("data", (Serializable) list);
				startActivity(intent);
			}
		});
	}

	private void addNum() {
		int curVal = Integer.parseInt(tvNum.getText().toString());
		tvNum.setText("" + (curVal + 1));
	}

	private void minusNum() {
		int curVal = Integer.parseInt(tvNum.getText().toString());
		if (curVal > 1) {
			tvNum.setText("" + (curVal - 1));
		}
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		super.onWindowFocusChanged(hasFocus);
		// iv.getLayoutParams().height = iv.getWidth();
	}

	public void save2Cart() {
		loadingDialog = new LoadingDialog(this);
		loadingDialog.setCancelable(true);
		loadingDialog.show();
		final ShoppingRecord record = new ShoppingRecord();
		RadioButton rgShop = (RadioButton) findViewById(rgShops.getCheckedRadioButtonId());
		RadioButton rgPhotoBrand = (RadioButton) findViewById(rgPhotoBrands.getCheckedRadioButtonId());
		RadioButton rgPhotoMaterial = (RadioButton) findViewById(rgPhotoMaterials.getCheckedRadioButtonId());
		RadioButton rgPhotoSize = (RadioButton) findViewById(rgPhotoSizes.getCheckedRadioButtonId());
		String others = "";
		for (int i = 0; i < rgOthers.getChildCount(); i++) {
			CheckBox checkBox = (CheckBox) rgOthers.getChildAt(i);
			if (checkBox.isChecked()) {
				others += "," + checkBox.getText().toString();
			}
		}
		record.setShop(rgShop.getText().toString());
		record.setPhotoBrand(rgPhotoBrand.getText().toString());
		record.setPhotoMatieral(rgPhotoMaterial.getText().toString());
		record.setPhotocnt(Integer.parseInt(tvNum.getText().toString()));
		record.setPhotoSize(rgPhotoSize.getText().toString());
		record.setOthers(others);
		String paths = "";
		for (String tmp : path) {
			paths += "," + tmp;
		}
		record.setPhotos(paths);
		new Thread() {
			public void run() {
				try {
					new DatabaseHelper(ImageActivity.this).insertData(record);
					handler.sendEmptyMessage(SAVECART);
				} catch (Exception e) {
					handler.sendEmptyMessage(SAVECART_FAIL);
				}
			};
		}.start();
	}
	
	@Override
	protected void onDestroy() {
		viewFlow.stopAutoFlowTimer();
		super.onDestroy();
	}
	
	static class MyHandler extends Handler {

		WeakReference<ImageActivity> context;

		public MyHandler(ImageActivity context) {
			this.context = new WeakReference<ImageActivity>(context);
		}

		@Override
		public void handleMessage(Message msg) {
			ImageActivity activity = context.get();
			switch (msg.what) {
			case SAVECART:
				activity.loadingDialog.dismiss();
				ToastUtil.showTips(activity, R.drawable.tips_smile, "已添加到购物车");
				activity.setResult(Activity.RESULT_OK, new Intent());
				activity.finish();
				break;
			case SAVECART_FAIL:
				activity.loadingDialog.dismiss();
				ToastUtil.showTips(activity, R.drawable.tips_smile, "添加失败");
				break;
			}
			super.handleMessage(msg);
		}
	}
}
